package org.ekstrabilet.ticket;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import org.ekstrabilet.ticket.beans.Ticket;
import org.ekstrabilet.ticket.logic.TicketLogic;
/**
 * @author Maciej Koch
 * Class represents shopping cart. Contains all ordered tickets and button to buy all. 
 */
public class CartPane extends JPanel{

	List<Ticket> tickets;
	List<JPanel> panes;
	JButton buy;
	JScrollPane scroller;
	JPanel pane;
	
	
	public CartPane() {
		tickets = new ArrayList<Ticket>();
		panes = new ArrayList<JPanel>();
	}
	
	/**
	 * Adds new ticket to list
	 * @param ticket
	 * to add
	 */
	public void addTicket(Ticket ticket) {
		tickets.add(ticket);
		init();
	}
	private void init() {
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		buy = new JButton("Buy");
		pane = new JPanel(new GridLayout(tickets.size(), 1));
		if(tickets.isEmpty()) buy.setVisible(false);
		else buy.setVisible(true);
		removeAll();
		for(Ticket t : tickets){
			JPanel p= new JPanel();
			p.add(new JLabel("Game: "+t.getGameId()));
			p.add(new JLabel("Stadium: "+t.getStadium().getName()));
			p.add(new JLabel("City: "+ t.getStadium().getCity()));
			p.add(new JLabel("Tribune: "+ t.getTribune()+""));
			p.add(new JLabel("Sector: "+ t.getSectorId()+""));
			p.add(new JLabel("Row: " + t.getRow()+""));
			p.add(new JLabel("Seat: " + t.getSeat()+""));
			panes.add(p);
			pane.add(p);
		}
		buy.addActionListener(new BuyListener());
		scroller = new JScrollPane(pane);
		add(scroller);
		add(buy);
	}
	private class BuyListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			for(Ticket t : tickets)
				TicketLogic.getInstance().addTicket(t);
			
			tickets.clear();
			init();	
			revalidate();
			repaint();
			JOptionPane.showMessageDialog(panes.get(0), "Printing...");
			
		}
		
	}
}
